<template>
  <div style="border: black 0px solid;background-color: #f6f6f6">

    <div style="margin-top: 20px;margin-bottom: 20px" class="AwsCenter">

      <!--   左边   -->
      <div style="border: 0px black solid;width: 700px;height: 700px;display: flex;flex-direction: column">

      <!--   日期啥的   -->
        <div style="border: 0px solid black;padding: 10px;display: flex;flex-direction: column;height: 100px">
          <div style="margin-left: auto;display: flex;flex-direction: row;height: 70px">
            <div style="margin-left: 5px">{{format(new Date(), 'yyyy年MM月dd日', { locale: zh })}}</div>
            <div style="margin-left: 20px">{{currentTime}}</div>
            <div style="margin-left: 20px">{{currentDayOfWeek}}</div>
            <div style="margin-left: 10px">{{ weather.description }}</div>
            <!-- 显示天气图标 -->
            <img style="width: 25px;height: 25px" :src="weather.iconUrl" :alt="weather.description" />
            <div style="margin-left: 10px">{{ weather.temperature }}°C</div>
          </div>

          <div style="margin-left: auto;display: flex;flex-direction: row;margin-top: 10px">
            <text>纹样有灵，织心成锦。每一次勾勒，都是与传统的对话。</text>
          </div>

        </div>


        <div style="display: flex;flex-direction: row">

          <div style="width: 40%;height:300px;border: 0px black solid;
          border-radius: 20px;background-color: #8adba0;
          margin-top: 20px;margin-right: 10px;padding: 20px;display: flex;flex-direction: column">
            <text>{{homepageForm.sectionName}}</text>
            <text>{{homepageForm.textContent}}</text>
          </div>

          <!--   轮播图   -->
          <div style="width: 60%;border: black 0px solid;margin-top: 20px">
            <el-carousel interval="4000" indicator-position="outside" style="border-radius: 20px">
              <el-carousel-item v-for="(item, index) in images"  :key="index" style="border-radius: 20px">
                <img :src="item.src" :alt="'Image ' + (index + 1)" style="width: 100%; height: auto; border-radius: 20px;" />
              </el-carousel-item>
            </el-carousel>
          </div>
        </div>





        <div
            class="upload-guide"
            @click="dialogVisible = true"
        >
          <div class="icon">🖼️</div>
          <h3>上传你的壮锦纹样</h3>
          <p>分享传统之美，传承民族文化<br>点击开始上传</p>
        </div>

      </div>

    <!--  公告    -->
      <div style="border: black 0px solid;width: 350px;height: 700px;margin-left:20px;background-color: white;border-radius: 20px" >
        <div style="margin-top: 20px" class="AwsCenter">
          <text style="font-size: 23px;font-weight: bold;">公 告 信 息</text>
        </div>
        <div style="border: #A9A9A9 1px solid;margin:10px 20px 10px 20px"></div>

        <div v-for="(item,index) in announceList" :key="item.id"
             :style="{
                width: '90%',
                display: 'flex',
                flexDirection: 'column',
                margin: '20px',
                padding: '10px',
                borderRadius: '20px',
                // 动态设置背景颜色
                backgroundColor: index === 0 ? '#e6a083' : '#f1f2f0'
              }"
        >
          <text :style="{fontWeight: 'bold', fontFamily: 'LiSong Pro Light', color: index === 0 ? 'white' : 'black'}">· 【{{item.title}}】</text>

          <text :style="{fontFamily: 'LiSong Pro Light', marginTop: '5px', color: index === 0 ? 'white' : 'black'}">{{item.announcementcontent}}</text>

          <div style="display: flex;flex-direction: row;marginTop: 5px;">
            <text :style="{fontFamily: 'NSimSun', fontWeight: 'bold', fontSize: '14px', color: index === 0 ? 'white' : 'black'}">发布人：{{item.authorname}}</text>
            <text :style="{fontFamily: 'NSimSun', fontWeight: 'bold', fontSize: '14px', marginLeft: '30px', color: index === 0 ? 'white' : 'black'}">{{convertUtcToLocal(item.createdat)}}</text>
          </div>


        </div>

      </div>


    </div>

<!--    <div style="border: 1px black solid;width: 100%;height: 60px;background-color: black;align-items: center" class="AwsCenter">
        <text style="color: white;font-size: x-small">如遇问题请联系？123456789</text>
    </div>-->



  </div>

  <!-- 分步审核表单弹窗 -->
  <el-dialog
      v-model="dialogVisible"
      title="纹样上传审核流程"
      width="800px"
      :close-on-click-modal="false"
      @closed="onDialogClosed"
  >
    <el-steps :active="currentStep" finish-status="success" align-center style="margin-bottom: 30px">
      <el-step title="上传图片" />
      <el-step title="填写信息" />
    </el-steps>

    <!-- 步骤 1：上传图片 -->
    <div v-show="currentStep === 0" class="step-content">
      <div style="text-align: center; padding: 20px 0">
        <el-upload
            drag
            :auto-upload="false"
            :on-change="handleUploadChange"
            :on-remove="handleRemove"
            :file-list="fileList"
            :limit="1"
            :on-exceed="handleExceed"
            accept="image/*"
            style="display: inline-block"
        >
          <el-icon class="el-icon--large"><UploadFilled /></el-icon>
          <div class="el-upload__text">
            将纹样图片拖到此处，或 <em>点击选择文件</em>
          </div>
          <template #tip>
            <div class="el-upload__tip">
              支持 JPG、PNG 等格式，建议尺寸清晰
            </div>
          </template>
        </el-upload>
      </div>

      <!-- 图片预览 -->
      <div v-if="previewUrl" class="preview-section" style="margin-top: 20px">
        <h4 style="color: #333; margin-bottom: 10px">图片预览</h4>
        <el-image
            :src="previewUrl"
            fit="contain"
            :preview-src-list="[previewUrl]"
            style="
                width: 100%;
                height: 200px;
                object-fit: contain;
                background: #f0f0f0;
                border-radius: 8px;
                box-shadow: 0 2px 8px rgba(0,0,0,0.1);
              "
        />
      </div>
    </div>

    <!-- 步骤 2：填写信息 -->
    <div v-show="currentStep === 1" class="step-content">
      <el-form :model="form" label-width="130px" ref="formRef" :rules="rules">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="纹样名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入纹样名称" />
            </el-form-item>

            <el-form-item label="纹样类型" prop="type">
              <el-select v-model="form.type" placeholder="请选择类型" style="width: 100%">
                <el-option label="几何纹" value="几何纹" />
                <el-option label="植物纹" value="植物纹" />
                <el-option label="动物纹" value="动物纹" />
                <el-option label="文字纹" value="文字纹" />
                <el-option label="人物纹" value="人物纹" />
                <el-option label="抽象纹" value="抽象纹" />
              </el-select>
            </el-form-item>

            <el-form-item label="所属地域" prop="region">
              <el-input v-model="form.region" placeholder="如：广西、贵州、云南" />
            </el-form-item>

            <el-form-item label="工艺难度" prop="difficultyLevel">
              <el-radio-group v-model="form.difficultyLevel">
                <el-radio label="初级" />
                <el-radio label="中级" />
                <el-radio label="高级" />
              </el-radio-group>
            </el-form-item>

            <el-form-item label="纹样功能角色" prop="patternRole">
              <el-select v-model="form.patternRole" placeholder="请选择角色" style="width: 100%">
                <el-option label="主纹" value="主纹" />
                <el-option label="辅纹" value="辅纹" />
                <el-option label="边饰" value="边饰" />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="文化寓意" prop="culturalMeaning">
              <el-input
                  type="textarea"
                  v-model="form.culturalMeaning"
                  :rows="3"
                  placeholder="描述纹样的象征意义、民族信仰等"
              />
            </el-form-item>

            <el-form-item label="历史背景描述" prop="historicalBackground">
              <el-input
                  type="textarea"
                  v-model="form.historicalBackground"
                  :rows="3"
                  placeholder="该纹样的起源、演变历史等"
              />
            </el-form-item>

            <el-form-item label="工艺流程说明" prop="craftProcess">
              <el-input
                  type="textarea"
                  v-model="form.craftProcess"
                  :rows="3"
                  placeholder="如：织造、刺绣、印染等工艺步骤"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <!-- 底部按钮 -->
    <template #footer>
      <div class="dialog-footer">
        <!-- 上一步 -->
        <el-button @click="prevStep" v-if="currentStep > 0">上一步</el-button>
        <!-- 下一步或提交 -->
        <el-button @click="nextStep" v-if="currentStep === 0" :disabled="!previewUrl">
          下一步
        </el-button>
        <el-button type="primary" @click="submitForm" v-else-if="currentStep === 1">
          提交审核
        </el-button>
        <el-button @click="dialogVisible = false">取消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import {getAnnouncementsService,getTextService} from '@/api/announce.js'
import {computed, onMounted, reactive, ref} from "vue";
import {useUserStore} from "@/stores/user/user.js";
import {format} from 'date-fns/format';
import zh from 'date-fns/locale/zh-CN';
const userStore=useUserStore()

import axios from 'axios';
import {getUserService} from "@/api/user.js";
import type {FormInstance, UploadFile, UploadInstance, UploadUserFile} from "element-plus";
import {ElMessage} from "element-plus";
import {upload} from "@/api/upload";

// 替换为你的API密钥和你选择的API URL
const apiKey = '6d1c72ba97c694c35db2358763ef9d6e';
const apiUrl = `https://api.openweathermap.org/data/2.5/weather?lat=31.299379&lon=120.619585&units=metric&lang=zh_cn&appid=${apiKey}`;

const loading = ref(true);
const error = ref<string | null>(null);
const weather = ref({
  city: '',
  temperature: 0,
  description: '',
  iconUrl: ''
});

// 定义图片数组，包含图片路径
const images = ref([
  { src: new URL('@/assets/mainImg/1.jpg', import.meta.url).href }, // 根据实际情况调整路径
  { src: new URL('@/assets/mainImg/2.jpg', import.meta.url).href },
  { src: new URL('@/assets/mainImg/3.jpg', import.meta.url).href }

]);

const fetchWeatherData = async () => {
  try {
    const response = await axios.get(apiUrl);
    const data = response.data;
    weather.value.city = data.name;
    weather.value.temperature = data.main.temp;
    weather.value.description = data.weather[0].description;

    // 使用OpenWeatherMap提供的图标URL
    weather.value.iconUrl = `https://openweathermap.org/img/wn/${data.weather[0].icon}@2x.png`;

    loading.value = false;
  } catch (err) {
    console.error('获取天气数据失败:', err);
    error.value = '无法获取天气信息，请稍后再试。';
    loading.value = false;
  }
};

// 定义一个响应式的 currentDayOfWeek 变量
const currentDayOfWeek = ref<string>('');

// 获取今天的星期并转换为中文
const getDayOfWeek = (): string => {
  const daysOfWeek = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
  const today = new Date();
  return daysOfWeek[today.getDay()];
};

// 定义一个响应式的 currentTime 变量
const currentTime = ref<string>('');

// 更新时间的函数
const updateTime = () => {
  // 使用 JavaScript 的原生方法格式化时间，去掉秒
  currentTime.value = new Date().toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit', hour12: false });
};

// 组件挂载时立即更新一次时间，并设置定时器每分钟更新一次

const user=ref('')

const announceList=ref([])

function convertUtcToLocal(utcDateStr: string): string {
  const date = new Date(utcDateStr);
  // 使用 'zh-CN' 区域和 'long' 格式来确保小时为24小时制
  return date.toLocaleString('zh-CN', { hour12: false });
}
onMounted(async ()=>{
  const userRes=await getUserService()
  if (userRes.code===200){
    user.value=userRes.data
  }

  //获取首页信息数据
  await getText()

  //获取公告列表
  const res=await getAnnouncementsService()
  if (res.code===200){
    //console.log(res)
    announceList.value=res.data
    console.log(announceList.value)
  }
  //获取天气信息
  await fetchWeatherData();

  currentDayOfWeek.value = getDayOfWeek();
  updateTime();
  //
  setInterval(updateTime, 1000); // 每隔一分钟调用一次自己

})
const formatDate=((datetime)=>{
  const str=datetime.toString().split(".")[0]
  return str.replace('T', ' ')
})

const getText=(async ()=>{
  const res=await getTextService()
  if (res!=undefined&&res.code===200){
    //console.log(res)
    homepageForm.value={...res.data[0]}
  }
})
const homepageForm=ref({
  id:'',
  sectionName:'',
  textContent:'',
  modifiedBy:''
})


// 弹框显示控制
const dialogVisible = ref(false)

// 当前步骤（0: 上传图片, 1: 填写信息）
const currentStep = ref(0)

// 文件列表
const fileList = ref<UploadUserFile[]>([])

const uploadFile=ref(null)

// 预览图 URL
const previewUrl = ref<string | null>(null)

// 表单引用
const formRef = ref<FormInstance>()

// 表单数据（userId 保留但不显示）
const form = reactive({
  userId: userStore.user.userid, // 实际使用中应从登录状态获取
  name: '',
  type: '',
  region: '',
  difficultyLevel: '',
  culturalMeaning: '',
  historicalBackground: '',
  craftProcess: '',
  patternRole: '辅纹',
  uploadedFilePath: ''
})

// 表单验证规则
const rules = {
  name: [{ required: true, message: '请输入纹样名称', trigger: 'blur' }],
  type: [{ required: true, message: '请选择纹样类型', trigger: 'change' }],
  region: [{ required: true, message: '请输入所属地域', trigger: 'blur' }],
  difficultyLevel: [{ required: true, message: '请选择工艺难度', trigger: 'change' }],
  culturalMeaning: [{ required: true, message: '请输入文化寓意', trigger: 'blur' }],
  patternRole: [{ required: true, message: '请选择纹样功能角色', trigger: 'change' }]
}

// 文件变更时处理（添加预览）
const handleUploadChange = (file: UploadFile) => {
  const reader = new FileReader()
  reader.onload = (e) => {
    previewUrl.value = e.target?.result as string
  }
  reader.readAsDataURL(file.raw as File)
  uploadFile.value=file
}

// 移除文件
const handleRemove = () => {
  fileList.value = []
  previewUrl.value = null
}

// 超出文件数量限制
const handleExceed = () => {
  ElMessage.warning('只允许上传一个文件')
}

// 上一步
const prevStep = () => {
  currentStep.value--
}

// 下一步
const nextStep = () => {
  if (!previewUrl.value) {
    ElMessage.warning('请先上传纹样图片')
    return
  }
  currentStep.value++
}
import {uploadPattern} from '@/api/uploadReview.js'
// 提交表单
const submitForm = async () => {
  if (!formRef.value) return

  //先上传云服务器

  //form.uploadedFilePath='http://booking-chengmj.oss-cn-beijing.aliyuncs.com/1760508495317/9322dad3cce841829674de8d2fe09e45/%E7%AA%97%E6%A0%BC%E8%BE%B9%E8%A7%92%E8%8A%B1%E8%BE%B9%E7%BA%B9%E6%A0%B71.png?Expires=4916182095&OSSAccessKeyId=LTAI5t7CSWd2dX2PdiDxjF9o&Signature=yxWyvM2jZ5nN2Y10UMhDVcR8gTE%3D'
  const res=await upload(uploadFile.value.raw)

  if (res.code===200){
    form.uploadedFilePath=res.message

    let res2= await uploadPattern(form)
    if (res2.code===200){

      ElMessage.success(res2.message)
      dialogVisible.value=false
    }

  }




}

// 关闭弹窗时重置状态
const onDialogClosed = () => {
  currentStep.value = 0
  fileList.value = []
  previewUrl.value = null
  // 保留 userId，重置其他字段
  form.name = ''
  form.type = ''
  form.region = ''
  form.difficultyLevel = ''
  form.culturalMeaning = ''
  form.historicalBackground = ''
  form.craftProcess = ''
  form.patternRole = '辅纹'
}

</script>

<style scoped>

.el-carousel__item h3 {
  display: flex;
  color: #475669;
  opacity: 0.75;
  line-height: 300px;
  margin: 0;
}

.el-carousel__item:nth-child(2n) {
  background-color: #99a9bf;
}

.el-carousel__item:nth-child(2n + 1) {
  background-color: #d3dce6;
}


.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.AwsCenter{
  display: flex;
  justify-content: center;

  //align-items: center;
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 110px;
  height: 110px;
  text-align: center;
}


.upload-guide {
  width: 100%;
  height: 270px;
  border-radius: 20px;
  background-color: #f9fafa;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  border: 2px dashed #d0e1d4;
  text-align: center;
  transition: all 0.3s ease;
  cursor: pointer;
}

.upload-guide:hover {
  border-color: #8bc3a1;
  background-color: #f0f7f2;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(138, 195, 161, 0.15);
}

.upload-guide .icon {
  font-size: 48px;
  margin-bottom: 12px;
}

.upload-guide h3 {
  margin: 0 0 8px 0;
  font-size: 18px;
  color: #2e3a4e;
  font-weight: 600;
}

.upload-guide p {
  margin: 0 20px 16px 20px;
  font-size: 14px;
  color: #6b7785;
  line-height: 1.5;
}

.upload-modal-content {
  padding: 0 20px;
}

.preview-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-top: 10px;
}

.preview-wrapper {
  width: 100%;
  height: 200px;
  display: flex;
  justify-content: center;
  align-items: center;
  overflow: hidden;
  background-color: #f9f9f9;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

.dialog-footer {
  text-align: right;
}
</style>